/*
 * @customMade: 赵宇
 * @Date: 2021-09-14 14:41:00
 * @LastEditTime: 2024-04-19 23:43:34
 * @LastEditors: zhao 13370229059@163.com
 * @FilePath: \yww-uni-app\store\index.js
 */
import { createStore } from 'vuex';

let lifeData = uni.getStorageSync('lifeData');

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['vuex_openid', 'vuex_user'];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
  // 判断变量名是否在需要存储的数组中
  if (saveStateKeys.indexOf(key) != -1) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmp = uni.getStorageSync('lifeData');
    // 第一次打开APP，不存在lifeData变量，故放一个{}空对象
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    // 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
    uni.setStorageSync('lifeData', tmp);
  }
};

export default createStore({
  state: {
    vuex_user: lifeData.vuex_user || {}
  },
  mutations: {
    $uStore(state, payload) {
      let nameArr = payload.name.split('.');
      let saveKey = '';
      let len = nameArr.length;
      if (nameArr.length >= 2) {
        let obj = state[nameArr[0]];
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]];
        }
        obj[nameArr[len - 1]] = payload.value;
        saveKey = nameArr[0];
      } else {
        state[payload.name] = payload.value;
        saveKey = payload.name;
      }
      saveLifeData(saveKey, state[saveKey]);
    }
  },
  actions: {},
  getters: {},
  modules: {}
});
